/*
 * store产品创建
 * @Author: ljb
 * @Date: 2018-03-27 17:53:51
 * @Last Modified by: kanglin
 * @Last Modified time: 2018-10-26 15:29:11
 */
<style lang="less" rel="stylesheet/less" type="text/less" scoped>
    .v-store-product-create {
		overflow-y: scroll;
		&::-webkit-scrollbar {
			display: none;
		}
        .product-form {
            width: 400px;
        }
    }
</style>
<style lang="less" rel="stylesheet/less" type="text/less">
    .v-store-product-create{
        .ivu-radio-group {
            margin: 0 0 0px 4.16666667%;
        }
        .btn {
            margin-top: 15px;
        }
    }
</style>
<template>
	<div
		:style="{'max-height':formMaxHeight(true)}"
		class="v-store-product-create">
		<div>
			<!-- <Row v-if="Number(getUserInfo.has_youzan) === 1">
				<i-col push="2">
					<Button
						type="primary"
						name="create__syncSale"
						@click="$emit('syncSale')">
						{{ $t('product.sync_youzan_sale') }}
					</Button>

					<Button
						type="ghost"
						style="margin-left: 8px"
						name="create__sync_youzan_inven"
						@click="$emit('syncInventory')">
						{{ $t('product.sync_youzan_inven') }}
					</Button>
				</i-col>
			</Row> -->

			<br>

			<Row
				type="flex"
				justify="start">
				<i-col push="1">
					<Form
						ref="formValidate"
						:model="formValidate"
						:rules="ruleValidate"
						:label-width="labelWidth(90, 140)"
						class="product-form">
						<!-- 类别 -->
						<Form-item
							:label="$t('product.category')"
							prop="category_id">
							<Select
								v-model="formValidate.category_id"
								clearable
								@on-change="changeCategory"
								@on-clear="clearCategory">
								<OptionGroup
									v-for="(item,key) in groupCategories"
									:key="key"
									:label="item.custom_type_name">
									<Option
										v-for="(value,key) in item.categories"
										:value="value.id"
										:key="key">{{ value.name }}</Option>
								</OptionGroup>
							</Select>
						</Form-item>
						<!-- 标题 -->
						<Form-item
							:label="$t('product.title')"
							prop="title">
							<i-input
								v-model="formValidate.title"
								:placeholder="$t('product.please_enter_title')"
								name="create__title"
								type="text"/>
						</Form-item>
						<!-- 简称 -->
						<Form-item
							:label="$t('product.name')"
							prop="name">
							<i-input
								v-model="formValidate.name"
								:placeholder="$t('product.please_enter_name')"
								name="create__name"
								type="text"/>
						</Form-item>
						<!-- 编码 -->
						<Form-item
							:label="$t('product.code')"
							prop="spu_code">
							<i-input
								v-model="formValidate.spu_code"
								:placeholder="$t('product.please_enter_code')"
								name="create__spu_code"
								type="text"/>
						</Form-item>
						<!-- 品牌 -->
						<Form-item
							:label="$t('product.brand')"
							prop="brand_id">
							<Select
								v-model="formValidate.brand_id"
								name="create__brand_id"
								clearable
								filterable
								@on-change="changeBrans"
								@on-clear="clearBrans">
								<Option
									v-for="( value , key ) in brands"
									:value="key + ''"
									:key="key">{{ value }}</Option>
							</Select>
						</Form-item>
						<!-- 系列 -->
						<Form-item
							v-show="has_assets"
							:label="$t('product.series')"
							:prop="has_assets ? 'series' : ''">
							<Select
								v-model="formValidate.series"
								clearable>
								<Option
									v-for="(item) in brandList"
									:value="String(item.id)"
									:key="item.id">{{ item.name }}</Option>
							</Select>
						</Form-item>

						<!-- 标签 -->
						<Form-item
							v-if="!has_assets"
							:label="$t('product.tag')"
							prop="product_tag_ids">
							<Select
								v-model="formValidate.product_tag_ids"
								multiple
								clearable
								filterable>
								<Option
									v-for="( value , key ) in productTags"
									:value="key+ ''"
									:key="key">{{ value }}</Option>
							</Select>
						</Form-item>
						<!-- 身体部位 -->
						<!-- <Form-item
							v-if="!has_assets"
							:label="$t('product.body_positions')"
							prop="body_position_ids">
							<Select
								v-model="formValidate.body_position_ids"
								:placeholder="$t('product.body_positions')"
								clearable
								multiple>
								<Option
									v-for="( item , key ) in positions"
									:value="item.id"
									:key="key">{{ item.name }}
								</Option>
							</Select>
						</Form-item> -->
						<!-- 性别 -->
						<Form-item
							v-show="!has_assets"
							:label="$t('product.gender')"
							prop="stock">
							<RadioGroup v-model="formValidate.sex">
								<Radio :label="0">{{ $t('product.general') }}</Radio>
								<Radio :label="1">{{ $t('product.male') }}</Radio>
								<Radio :label="2">{{ $t('product.female') }}</Radio>
							</RadioGroup>
						</Form-item>
						<!-- 产品价格 -->
						<Form-item
							:label="$t('product.sell_price')"
							prop="sell_price">
							<InputNumber
								:min="0"
								:max="100000000"
								v-model="formValidate.sell_price"
								:placeholder="$t('product.please_enter_sell_price')"
								name="create__sell_price"/>
						</Form-item>
						<!-- 划线价 -->
						<Form-item
							:label="$t('product.market_price')"
							prop="market_price">
							<InputNumber
								:min="0"
								:max="100000000"
								v-model="formValidate.market_price"
								:placeholder="$t('product.please_enter_market_price')"
								name="create__market_price"/>
						</Form-item>
						<!-- 优先级 -->
						<Form-item
							:label="$t('product.priority')"
							prop="priority">
							<InputNumber
								:max="100000"
								:min="0"
								v-model="formValidate.priority"
								:placeholder="$t('product.please_enter_priority')"
								name="create__priority"/>
						</Form-item>
						<!-- 模型文件 -->
						<Form-item
							v-show="has_assets"
							:label="$t('product.model_file')"
							prop="asset_id">
							<Select
								v-model="formValidate.asset_id"
								:placeholder="$t('product.no_model')"
								clearable>
								<Option
									v-for="model in models"
									:value="String(model.id)"
									:key="model.id">{{ model.code }}</Option>
							</Select>
						</Form-item>
						<!-- 商品链接类型 -->
						<Form-item
							:label="$t('product.tb_link_type')"
							name="create__form"
							prop="product_url_type_id">
							<Select
								v-model="formValidate.product_url_type_id"
								clearable
								name="create__product_url_type_id"
								filterable>
								<Option
									v-for="chain in outerChain"
									:value="chain.id + ''"
									:key="chain.id">{{ chain.name }}</Option>
							</Select>
						</Form-item>
						<!-- 商品链接 -->
						<Form-item
							v-if="formValidate.product_url_type_id"
							:label="$t('product.tb_product_link')"
							:rules="[
								{
									required: true,
									message: $t('validate.required', { field: (productUrlType + $t('product.tb_product_link')) }),
									trigger: 'blur,change',
								},
								{
									type: 'url',
									message: $t('validate.url', { field: (productUrlType + $t('product.tb_product_link')) }),
									trigger: 'blur,change',
								},
							]"
							prop="product_url">
							<i-input
								v-model="formValidate.product_url"
								:placeholder="$t('product.please_enter_tb_link')"
								name="create__product_url"
								type="text"/>
						</Form-item>
						<!-- 缩略图 -->
						<Form-item
							:label="$t('product.thumb')"
							prop="thumb">
							<Uploader
								ref="thumb"
								@on-remove="(file)=>{handleRemove('thumb',file)}"
								@on-change="(file)=>{handleChange('thumb',file)}">
								{{ $t('product.img_tip') }}
							</Uploader>
						</Form-item>
						<!-- 颜色缩略图 -->
						<Form-item
							v-show="has_assets"
							:label="$t('product.color_thumb')"
							prop="color_thumb">
							<Uploader
								ref="color_thumb"
								@on-remove="(file)=>{handleRemove('color_thumb',file)}"
								@on-change="(file)=>{handleChange('color_thumb',file)}">
								{{ $t('product.img_tip') }}
							</Uploader>
						</Form-item>

						<Form-item>
							<Button
								type="primary"
								name="create__submit"
								@click="handleSubmit('formValidate')">
								{{ $t('common.submit') }}
							</Button>
							<Button
								type="ghost"
								style="margin-left: 8px"
								name="create__reset"
								@click="handleReset('formValidate')">
								{{ $t('common.reset') }}
							</Button>
						</Form-item>

					</Form>
				</i-col>
			</Row>
		</div>
	</div>
</template>

<script>

import labelWidthMixin from 'src/views/mixins/labelWidthMixin';
import { validateImage, validateUpdateImage } from 'src/validate'; // 引入校验文件
import { computedFormMaxHeight } from 'src/views/mixins/computedFormMaxHeight';

import { mapGetters } from 'vuex';
import Uploader from 'src/views/component/Uploader';

export default {
	name: 'ProductCreate',
	components: {
		Uploader,
	},
	mixins: [labelWidthMixin, computedFormMaxHeight],
	props: {
		brands: {
			type: Object,
			default() {
				return {};
			},
		},
		groupBrands: {
			type: Array,
			default() {
				return [];
			},
		},
		outerChain: {
			type: Array,
			default() {
				return [];
			},
		},
		categories: {
			type: Array,
			default() {
				return [];
			},
		},
		groupCategories: {
			type: Array,
			default() {
				return [];
			},
		},
		productTags: {
			type: Object,
			default() {
				return {};
			},
		},
		modelsGroup: {
			type: Array,
			default() {
				return [];
			},
		},
		taobaoItem: {
			type: Object,
			default() {
				return {};
			},
		},
		showTaobao: {
			type: Boolean,
			default() {
				return false;
			},
		},
		loading: {
			type: Boolean,
			default() {
				return false;
			},
		},

		positions: {
			type: Array,
			default() {
				return [];
			},
		},
		cosmeticMaterials: {
			type: Array,
			default() {
				return [];
			},
		},
	},

	data() {
		return {
			formValidate: {
				category_id: '', // 类别

				title: '', // 标题

				name: '', // 简称

				spu_code: '', // 编码

				brand_id: '', // 品牌

				series: '', // 系列

				material: '', // 材质

				product_mod_id: 0,

				product_tag_ids: [], // 标签

				body_position_ids: [], // 身体部位

				sex: 0, // 性别

				asset_id: '', // 模型文件

				sell_price: 0, // 产品价格

				market_price: 0, // 划线价

				priority: 0, // 优先级

				product_url_type_id: '', // 商品链接类型

				product_url: '', // 商品链接

				thumb: null, // 缩略图

				color_thumb: null, // 颜色缩略图
			}, // 新建产品时的表单

			has_assets: true, // 分类是否有素材

			models: [], // 模型文件

			ruleValidate: { // 表单验证规则
				product_url_type_id: [
					{
						message: this.$t('validate.required', { field: this.$t('product.tb_link_type') }),
						trigger: 'blur,change',
					},
				],
				product_url: [
					{
						required: true,
						message: this.$t('validate.required', { field: this.$t('product.tb_product_link') }),
						trigger: 'blur,change',
					},
					{
						type: 'url',
						message: this.$t('validate.url', { field: this.$t('product.tb_product_link') }),
						trigger: 'blur,change',
					},
				],
				category_id: [
					{
						required: true,
						type: 'number',
						message: this.$t('validate.required', { field: this.$t('product.category') }),
						trigger: 'blur,change',
					},
				],
				brand_id: [
					{
						required: true,
						message: this.$t('validate.required', { field: this.$t('product.brand') }),
						trigger: 'blur,change',
					},
				],
				series: [
					{
						required: true,
						message: this.$t('validate.required', { field: this.$t('product.series') }),
						trigger: 'blur,change',
					},
				],
				material: [
					{
						message: this.$t('validate.required', { field: this.$t('product.material') }),
						trigger: 'blur,change',
					},
				],
				product_tag_ids: [
					{
						required: true,
						type: 'array',
						message: this.$t('validate.required', { field: this.$t('product.tag') }),
						trigger: 'blur,change',
					},
				],
				asset_id: [
					{
						message: this.$t('validate.required', { field: this.$t('product.model_file') }),
						trigger: 'blur,change',
					},
				],
				title: [
					{
						required: true,
						message: this.$t('validate.required', { field: this.$t('product.title') }),
						trigger: 'blur,change',
					},
				],
				name: [
					{
						required: true,
						message: this.$t('validate.required', { field: this.$t('product.name') }),
						trigger: 'blur,change',
					},
				],
				spu_code: [
					{
						required: true,
						message: this.$t('validate.required', { field: this.$t('product.code') }),
						trigger: 'blur,change',
					},
				],
				market_price: [
					{
						// required: true,
						type: 'number',
						message: this.$t('validate.required', { field: this.$t('product.market_price') }),
						trigger: 'blur,change',
					},
				],
				sell_price: [
					{
						required: true,
						type: 'number',
						message: this.$t('validate.required', { field: this.$t('product.sell_price') }),
						trigger: 'blur,change',
					},
				],
				priority: [
					{
						required: true,
						type: 'number',
						message: this.$t('validate.required', { field: this.$t('product.priority') }),
						trigger: 'blur,change',
					},
				],
				thumb: [
					{ required: true, validator: validateImage, trigger: 'blur,change' },
				],

				color_thumb: [
					{ validator: validateUpdateImage, trigger: 'blur,change' },
				],
				body_position_ids: [
					{
						required: true,
						type: 'array',
						message: this.$t('validate.required', { field: this.$t('product.body_positions') }),
						trigger: 'blur,change',
					},
				],

			},

			brandList: [], // 系列信息

		};
	},

	computed: {
		...mapGetters('userToken', [
			'getUserInfo',
		]),
		// 产品类型的name值
		productUrlType() {
			const { product_url_type_id } = this.formValidate;
			const selected_type = this.outerChain.filter(chain => parseInt(chain.id, 10) === parseInt(product_url_type_id, 10))[0];

			return selected_type.name || '';
		},
	},

	methods: {

		/**
		 * 改变类型与模型关联文件
		 * @param  {Number} category_id {改变select获取到value值}
		 * @return {undefined}
		 */
		changeCategory(category_id) {
			if (category_id === '') { // 清空
				this.has_assets = true;
				this.resetTagAndPositionOptions();
				return;
			}
			const has_assets = this.hasModelAssets(category_id);
			this.models = this.takeModels(category_id);
			if (has_assets) {
				this.resetTagAndPositionOptions();
			} else {
				this.formValidate.asset_id = null;
			}
			this.has_assets = has_assets;
		},

		/**
		 * 改变品牌与系列文件
		 * @param {String} brand_id {改变select获取到value值}
		 * @return {undefined}
		 */
		changeBrans(brand_id) {
			this.groupBrands.forEach((item) => {
				if (String(item.id) === brand_id) {
					this.brandList = item.brand_series;
				}
			});
			this.formValidate.series = '';
		},

		/**
		 *清空类型与模型关联文件
		 * @return {undefined}
		 */
		clearBrans() {
			this.brandList = [];
		},

		/**
		 *  重置表单/身体部位选项
		 *  @return {Array}
		 */
		resetTagAndPositionOptions() {
			this.formValidate.product_tag_ids = [];
			this.formValidate.body_position_ids = [];
		},

		/**
		 *  获取模型
		 *  @param {number} category_id {类型选中的值value}
		 *  @return {array} models
		 */
		takeModels(category_id) {
			let models = [];
			this.modelsGroup.forEach((item) => {
				if (item.category_id === category_id) {
					models = item.assets;
				}
			});
			return models;
		},

		/**
		 * 是否有模型素材
		 * @param {number} category_id {类型选中的值value}
		 * @return {boolean} has_assets
		 */
		hasModelAssets(category_id) {
			const [category] = this.categories.filter(item => item.id === category_id);
			return category && !!category.has_asset;
		},

		/**
		 *清空类型与模型关联文件
		 * @return {Array}
		 */
		clearCategory() {
			this.models = [];
		},

		/**
		 * 选择图片
		 * @param {Object} file {选择的文件对象集合}
		 * @param {String} field {icon}
		 * @return {undefined}
		 */
		handleChange(field, { file }) {
			this.formValidate[field] = file;
			this.$refs.formValidate.validateField(field);
		},

		/**
		 * 删除图片
		 * @param {String} field {icon}
		 * @return {undefined}
		 */
		handleRemove(field) {
			this.formValidate[field] = null;
			this.$refs.formValidate.validateField(field);
		},

		/**
         * 提交表单
         * @param  {string} name {表单的ref}
         * @return {undefined}
         */
		handleSubmit(name) {
			if (this.loading) return;

			this.$refs[name].validate((valid) => {
				if (valid) {
					this.$emit('post', this.formDataCreate());
				} else {
					this.$Message.error(this.$t('common.exist_empty_field'));
				}
			});
		},

		/**
         * 重置表单
         * @param  {string} name {表单的ref}
         * @return {undefined}
         */
		handleReset(name) {
			this.$refs.thumb.reset();
			this.$refs.color_thumb.reset();
			this.$refs[name].resetFields();

			this.$emit('clear');

			this.$emit('remove');
		},

		/**
         * 手动拼接表单数据
         * @return {Object} {拼接好的表单数据}
         */
		formDataCreate() {
			const new_object = {
				category_id: this.formValidate.category_id,

				brand_id: this.formValidate.brand_id,

				product_mod_id: 0,

				title: this.formValidate.title,

				name: this.formValidate.name,

				spu_code: this.formValidate.spu_code,

				market_price: this.formValidate.market_price,

				sell_price: this.formValidate.sell_price,

				priority: this.formValidate.priority,

				thumb: this.formValidate.thumb,

				color_thumb: this.formValidate.color_thumb,

				product_url_type_id: this.formValidate.product_url_type_id,

				product_url: this.formValidate.product_url ? this.formValidate.product_url : null,

				asset_id: this.has_assets ? this.formValidate.asset_id : null,

				sex: !this.has_assets ? this.formValidate.sex : null,

				product_tag_ids: !this.has_assets ? this.formValidate.product_tag_ids : null,

				body_position_ids: !this.has_assets ? this.formValidate.body_position_ids : null,

				cosmetic_material_id: this.formValidate.material ? this.formValidate.material : null,

				brand_series_id: this.formValidate.series ? this.formValidate.series : null,
			};

			const form_data = new FormData();

			Object.keys(this.skipNulls(new_object))
				.forEach((key) => {
					switch (key) {
					case 'product_tag_ids':
						if (new_object[key].length > 0) {
							new_object[key].forEach((tag, index) => {
								form_data.append(`${key}[${index}]`, tag);
							});
						}

						break;
					case 'body_position_ids':
						if (new_object[key].length > 0) {
							new_object[key].forEach((tag, index) => {
								form_data.append(`${key}[${index}]`, tag);
							});
						}

						break;
					default:
						form_data.append(key, new_object[key]);

						break;
					}
				});
			return form_data;
		},

		/**
		 * 跳过对象中的 null 值元素
		 * @param {Object} source {手动拼接对象}
		 * @returns {Object} target
		 */
		skipNulls(source) {
			const target = {};
			Object.keys(source)
				.forEach((key) => {
					const is_null = typeof source[key] === 'object' && !source[key];
					if (!is_null) {
						Object.assign(target, { [key]: source[key] });
					}
				});
			return target;
		},

	},
};
</script>
